using System;
using System.Collections.Generic;
using Azure.Domain.Messages;
using Azure.Domain.Models;
using Azure.Infrastructure;
using Microsoft.WindowsAzure.StorageClient;

namespace Azure.Domain.Services
{
    public class CommentService : ICommentService
    {
        private readonly IRepository<Comment> _commentRepository;
        private readonly IQueue<NewCommentMessage> _commentQueue;

        public CommentService(IRepository<Comment> commentRepository, IQueue<NewCommentMessage> commentQueue)
        {
            _commentRepository = commentRepository;
            _commentQueue = commentQueue;
        }

        public IEnumerable<Comment> LoadComments(Post post)
        {
            return _commentRepository.Load(post.RowKey);
        }

        public IEnumerable<Comment> Recent(int last)
        {
            return _commentRepository.Last(last);
        }

        public Comment CommentOn(Post post, CommentRequest request)
        {
            Comment comment = CreateComment(post, request);
            
            _commentQueue.Enqueue(new NewCommentMessage(request, post));
            
            return comment;
        }

        protected virtual Comment CreateComment(TableServiceEntity entity, CommentRequest request)
        {
            return new Comment(Key.Partition(entity), Key.Row(request.Created))
                {
                    Author = request.Author,
                    Body = request.Body,
                    Email = request.Email,
                    Website = request.Website
                };
        }

        public void Process(NewCommentMessage message)
        {
            Comment comment = CreateComment(message.Post, message.Request);
            _commentRepository.Insert(comment);
        }

        public void Remove(Comment comment)
        {
            _commentRepository.Delete(comment);
        }
    }
}